package easymall.service;

import com.alibaba.fastjson.JSONObject;
import easymall.dao.ProductsDao;
import easymall.po.Products;
import easymall.pojo.MyPage;
import easymall.pojo.MyProducts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Service("productsService")
public class ProductsServiceImpl implements ProductsService {

	@Autowired
	private ProductsDao productsDao;
	@Autowired
	private RestTemplate restTemplate;

	@Override
	public List<Products> prodlist(Map<String, Object> map) {
		List<Products> products = productsDao.prodlist(map);
		return products;
	}

	@Override
	public Products oneProduct(String pid) {
		return productsDao.oneProduct(pid);
	}

	@Override
	public List<Products> proclass(Integer category) {
		return productsDao.proclass(category);
	}

	@Override
	public String save(MyProducts myproducts) {
		// 1.判断后缀是否合法
		// 获取图名称，后缀名称
		String originName = myproducts.getImgurl().getOriginalFilename();

		// 截取后缀substring split(".jpg" ".png")
		String extName = originName.substring(originName.lastIndexOf("."));

		if (!(extName.equalsIgnoreCase(".jpg") || extName.equalsIgnoreCase(".png")
				|| extName.equalsIgnoreCase(".gif"))) {
			// 图片后缀不合法
			return "图片后缀不合法";
		}

		// 判断木马（java的类判断是否是图片属性，也可引入第三方jar包判断
		try {
			BufferedImage bufImage = ImageIO.read(myproducts.getImgurl().getInputStream());
			bufImage.getHeight();
			bufImage.getWidth();
		} catch (Exception e) {
			return "该文件不是图片！";
		}

		// 2.创建upload开始的一个路径
		// 生成多级路径
		String imgurl = "";
		// /a/2/e/a/2/3/j/p
		for (int i = 0; i < 8; i++) {
			imgurl += "/" + Integer.toHexString(new Random().nextInt(16));
		}

		String realpath = System.getProperty("user.dir")+"/tmp";   //缓存路径
		File dir = new File(realpath);
		if(!dir.exists()){
			dir.mkdirs();
		}

		//file  ->  f:/tmp/a/2/3/originName ->  f:/tmp/a.2.2.3.originName
		File file = new File(realpath + trans(imgurl) + '.'+originName); // 绝对路径

		// 上传文件
		try {
			myproducts.getImgurl().transferTo(file);
//			img.transferTo(file);  //先保存到本地缓存起来
			uploadFile2Remote(realpath, file.getName()); //上传到远程
			file.delete();  //将临时存储的文件删除
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 拼接图片存入数据库的路径
		imgurl = "/upload" + imgurl + "/" + originName;
		String id = UUID.randomUUID().toString();
		Products products = new Products();
		products.setId(id);
		products.setName(myproducts.getName());
		products.setCategory(myproducts.getCategory());
		products.setPrice(myproducts.getPrice());
		products.setPnum(myproducts.getPnum());
		products.setImgurl(imgurl);
		products.setDescription(myproducts.getDescription());
		if (productsDao.findByImgurl(products.getImgurl()) == null) {
			productsDao.save(products);
		} else {
			String fname = imgurl.substring(0, imgurl.lastIndexOf("."));
			imgurl = fname + System.currentTimeMillis() + extName;
			products.setImgurl(imgurl);
			System.out.println(products.getImgurl());
			productsDao.save(products);
		}
		return "商品添加成功";
	}

	/********************** 分页相关 **************************/


	@Override
	public List<Products> getProductsByPage(Integer page) {
		MyPage mypage = new MyPage(page);
		return productsDao.getProductsByPage(mypage);
	}

	@Override
	public int getTotalPageByProducts() {
		return (productsDao.getProductsCount() - 1) / MyPage.size + 1;
	}

	@Override
	public String updatePruduct(MyProducts myproducts, String id) {
		Products products = new Products();
		
		//用户有上传图片才读取图片
		if(myproducts.getImgurl().getSize()!=0) {
			String imgurl = checkimg(myproducts.getImgurl());
			if(imgurl.equals("0")) {
				return "图片后缀不合法！";
			}else if(imgurl.equals("1")) {
				return "该文件不是图片!";
			}
			String originName = myproducts.getImgurl().getOriginalFilename();
			String extName = originName.substring(originName.lastIndexOf("."));
			products.setImgurl(imgurl);
			if (productsDao.findByImgurl(products.getImgurl()) != null) {
				String fname = imgurl.substring(0, imgurl.lastIndexOf("."));
				imgurl = fname + System.currentTimeMillis() + extName;
				products.setImgurl(imgurl);
				System.out.println(products.getImgurl());
				
			}
		}
		
		products.setId(id);
		products.setName(myproducts.getName());
		products.setCategory(myproducts.getCategory());
		products.setPrice(myproducts.getPrice());
		products.setPnum(myproducts.getPnum());
		products.setDescription(myproducts.getDescription());
		if(productsDao.updatePruduct(products)==1) {
			return "更新成功";
		}else {
			return "数据库错误";
		}
	}

	@Override
	public int delProduct(String id) {
		return productsDao.delProduct(id);
	}

	// 检查图片是否合法
	// "图片后缀不合法"
	// "该文件不是图片！"
	// imgurl
	public String checkimg(MultipartFile img) {
		// 1.判断后缀是否合法
		// 获取图名称，后缀名称
		String originName = img.getOriginalFilename();

		// 截取后缀substring split(".jpg" ".png")
		String extName = originName.substring(originName.lastIndexOf("."));

		if (!(extName.equalsIgnoreCase(".jpg") || extName.equalsIgnoreCase(".png")
				|| extName.equalsIgnoreCase(".gif"))) {
			// 图片后缀不合法
			return "0";
		}

		// 判断木马（java的类判断是否是图片属性，也可引入第三方jar包判断
		try {
			BufferedImage bufImage = ImageIO.read(img.getInputStream());
			bufImage.getHeight();
			bufImage.getWidth();
		} catch (Exception e) {
			return "1";
		}

		// 2.创建upload开始的一个路径
		// 生成多级路径
		String imgurl = "";     // /a/2/e/a/2/3/j/p
		for (int i = 0; i < 8; i++) {
			imgurl += "/" + Integer.toHexString(new Random().nextInt(16));
		}

		String realpath = System.getProperty("user.dir")+"/tmp";   //缓存路径
		File dir = new File(realpath);
		if(!dir.exists()){
			dir.mkdirs();
		}

		//file  ->  f:/tmp/a/2/3/originName ->  f:/tmp/a.2.2.3.originName
		File file = new File(realpath + trans(imgurl) + '.'+originName); // 绝对路径

		// 上传文件
		try {
			img.transferTo(file);  //先保存到本地缓存起来
			uploadFile2Remote(realpath, file.getName()); //上传到远程
			file.delete();  //将临时存储的文件删除
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 拼接图片存入数据库的路径
		imgurl = "/upload" + imgurl + "/" + originName;
		return imgurl;
	}


	/**
	 * 比如：  F:/tmp   1.txt    -->  上传到远程 upload/1.txt
	 *        F:/tmp   2.3.4.txt ->  上传到远程 upload/2/3/4.txt
	 */
	//给本机图片路径，上传到远程指定地方
	private boolean uploadFile2Remote(String filePath, String fileName){
		final String url = "http://10.0.0.100:8087/upload";
		//设置请求头
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("multipart/form-data;charset=UTF-8");
		headers.setContentType(type);

		//设置请求体，注意是LinkedMultiValueMap
		FileSystemResource fileSystemResource = new FileSystemResource(filePath+"/"+fileName);
		MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
		form.add("file", fileSystemResource);
		form.add("filename",fileName);

		//用HttpEntity封装整个请求报文
		HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);

		String s = restTemplate.postForObject(url, files, String.class);
		JSONObject jsonObject = JSONObject.parseObject(s);
		if("1".equals(jsonObject.getString("resultCode"))){
//            System.out.println("上传成功");
			return true;
		}
//        System.out.println("上传失败");
		return false;
	}

	//  /a/b/c -> /a.b.c
	private String trans(String origin){
		String s = origin;
		s = s.replace('/', '.');
		s = s.replaceFirst(".","/");
		return s;
	}
}
